package com.newtouch.bxzs.business.personal.controller;

import cn.hutool.core.codec.Base64Decoder;
import cn.hutool.core.codec.Base64Encoder;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.newtouch.bxzs.business.enclosure.service.AttachmentService;
import com.newtouch.bxzs.business.personal.service.PersonalService;
import com.newtouch.bxzs.common.base.BaseErrorEnum;
import com.newtouch.bxzs.common.base.BaseException;
import com.newtouch.bxzs.common.base.em.AttachmentEnum;
import com.newtouch.bxzs.common.base.em.CompanyParameterTypeEnum;
import com.newtouch.bxzs.common.base.model.vo.EnclosureVO;
import com.newtouch.bxzs.common.base.response.BaseResponse;
import com.newtouch.bxzs.common.base.response.RespGenerator;
import com.newtouch.bxzs.common.base.util.CooperationCompanyUtils;
import com.newtouch.bxzs.common.base.util.RedisUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 图片测试Controller类
 *
 * <p>
 * <b>History:</b>
 * <table border="1">
 * <tr>
 * <th>Date</th>
 * <th>Operator</th>
 * <th>Memo</th>
 * </tr>
 * <tr>
 * <td>2021年3月25日</td>
 * <td>Amour</td>
 * <td>Create</td>
 * </tr>
 * </table>
 *
 * @author Amour
 *
 * @version 1.0.0
 * @since 1.0.0
 */
@Api(tags = "合作公司用户头像")
@RestController
@RequestMapping("/cooperation")
public class UserAvatarController {

    @Autowired
    private AttachmentService attachmentService;

    @Autowired
    private PersonalService personalService;
    @Value("${file.basePath}")
    private String basePath;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private CooperationCompanyUtils cooperationCompanyUtils;

    private static final String IS_NULL = "null";

    /**
     * 获取合作公司用户头像,提供给对端调用,记得开放接口权限白名单 GET接口,只需要修改SecurityConfig
     *
     * @return
     * @throws IOException
     */
    @SuppressWarnings("unchecked")
    @GetMapping("/sendUserImage")
    @ApiIgnore
    public BaseResponse<String> sendUserImage(@RequestParam String userJobNumber) throws IOException {
        FileInputStream fileInput = null;
        ByteArrayOutputStream byteOutput = null;
        byte[] result = null;
        try {
            String image = getImageUrl(userJobNumber);
            // 此处获取用户头像的路径,用于生成File对象
            File file = new File(basePath+image);
            fileInput = new FileInputStream(file);
            byteOutput = new ByteArrayOutputStream();
            byte[] b = new byte[1024];
            int n = -1;
            while ((n = fileInput.read(b)) != -1) {
                byteOutput.write(b, 0, n);
            }
            fileInput.close();
            byteOutput.close();
            result = byteOutput.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fileInput != null) {
                fileInput.close();
            }
            if (byteOutput != null) {
                byteOutput.close();
            }
        }
/*        if (result == null) {
            throw new BaseException(BaseErrorEnum.NOT_FOUND);
        }*/
        // 转换为base64
        return RespGenerator.returnOK(Base64Encoder.encode(result));
    }

    /**
     * 获取合作公司用户头像，本端调用.produces标识返回图片类型,JPEG适用于JPG、JPEG、PNG,其他类型的图片可以测试一下
     *
     * @return
     * @throws IOException
     */
    @GetMapping(value = "/getUserImage", produces = MediaType.IMAGE_JPEG_VALUE)
    @ResponseBody
    @ApiOperation(" 获取合作公司用户头像")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userJobNumber", value = "合作公司用户工号", type = "String", required = true),
            @ApiImplicitParam(name = "unifiedSocialCreditCode", value = "合作公司统一社会信用代码", type = "String", required = true)
    })
    public byte[] getUserImage(@RequestParam String userJobNumber,@RequestParam String unifiedSocialCreditCode) throws IOException {
        Map paramMap = new HashMap<>(1);
        paramMap.put("userJobNumber",userJobNumber);
        // 此处调用获取合作公司用户头像接口,接口地址从数据库或缓存获取
        String url = cooperationCompanyUtils.getCompanyUrl(unifiedSocialCreditCode,
                CompanyParameterTypeEnum.USER_IMAGE.getCode());
        if (StringUtils.isEmpty(url)){
            throw new BaseException("-1", "合作公司参数为空");
        }
        String jsonString = HttpUtil.get(url,paramMap);
        BaseResponse<?> result = JSONUtil.toBean(jsonString, BaseResponse.class);
        if (!BaseErrorEnum.SUCCESS.getResultCode().equals(result.getCode())) {
            throw new BaseException(result.getCode(), result.getMessage());
        }
        if (result == null || result.getData() == null) {
            // 调用接口没有获取到值时抛出异常
            throw new BaseException(BaseErrorEnum.INTERNAL_SERVER_ERROR);
        }
        if (IS_NULL.equals(result.getData().toString())){
            return null;
        }
        // base64解码返回,通过@ResponseBody注解转换为图片
        return Base64Decoder.decode(result.getData().toString());
    }

    /**
     * 获取用户头像url
     * @param userJobNumber 用户工号
     * @return 头像url
     */
    public String getImageUrl(String userJobNumber){
        String userId = personalService.getUserId(userJobNumber);
        /* 获取附件 */
        HashMap<String, List<String>> result = attachmentService.getEnclosureList(new EnclosureVO(userId, null));
        if (result != null) {
            // 设置头像地址
            List<String> list = result.get(String.valueOf(AttachmentEnum.DETAIL_PICTURE.getCode()));
            if (list != null) {
                for (String url : list) {
                    return url;
                }
            }
        }else {
            throw new BaseException(BaseErrorEnum.INTERNAL_SERVER_ERROR);
        }
        return null;
    }
}
